const fs = require('fs')
var path = require("path")
const axios = require('axios')
const config = require('../config/config')


class func {

    //是否为空
    empty(value){
        if(typeof value === 'undefined' || value === '' ) return true
        return false
    }
    //变量初始化
    varInit(value, type='string'){
        if(type == 'int')    value = isNaN(parseInt(value)) ? 0 : parseInt(value)
        if(type == 'num')    value = isNaN(Number(value)) ? 0 : Number(value)
        if(type == 'string') value = (typeof value === 'undefined') ? '' : value.toString()
        return value
    }
    //JSON序列化
    toJson(data={}, code = 200, msg = ''){
        //this.set("Content-Type", "application/json")
        return { code, msg, data }
    }
    //时间格式化 demo:dateFormat("yyyy-MM-dd hh:mm:ss",crtTime)
    dateFormat(fmt, date){
        var o = {
            "M+" : date.getMonth()+1,                 //月份
            "d+" : date.getDate(),                    //日
            "h+" : date.getHours(),                   //小时
            "m+" : date.getMinutes(),                 //分
            "s+" : date.getSeconds(),                 //秒
            "q+" : Math.floor((date.getMonth()+3)/3), //季度
            "S"  : date.getMilliseconds()             //毫秒
        };   
        if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length))
        for(var k in o) if(new RegExp("("+ k +")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
        return fmt;   
    }

    // 递归创建目录(同步): demo:mkdirsSync('hello/a/b/c');
    mkdirsSync(dirname, mode){
        if(fs.existsSync(dirname)){
            return true;
        }else{
            if(this.mkdirsSync(path.dirname(dirname), mode)){
                fs.mkdirSync(dirname, mode);
                return true;
            }
            return false;
        }
    }
	//写日志(异步)
	async log(data, log_type='default'){
        let time_dir = this.dateFormat("yyyy-MM-dd", new Date())
        let dir = `./static/log/${time_dir}/`
        this.mkdirsSync(dir)
        fs.appendFile(dir+`${log_type}.txt`,  data+'\r\n', (error)  => {
            if (error){
                console.log("log failed!" + error.message);
                return false
            } 
            return true
        })
	}

    //封装HTTP get方法
    httpGet(url, params={}, timeout=10){
        return new Promise((resolve,reject) => {
            axios.get(url,{params:params},{timeout: timeout*1000}).then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
        })
    }
    //封装HTTP post方法
     httpPost(url, params={}, timeout=10){
        return new Promise((resolve,reject) => {
          axios.post(url,params,{timeout: timeout*1000}).then(response => {
                resolve(response.data);
            },err => {
                reject(err)
            })
        })
    }

}
module.exports = new func()